package com.atguigu.gmall.index.aspect;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.index.annotation.GmallCache;
import jodd.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Aspect
@Component
public class GmallCacheAspect {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private RBloomFilter<String> bloomFilter;

    @Around("@annotation(com.atguigu.gmall.index.annotation.GmallCache)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取目标方法对象
        Method method = signature.getMethod();
        //获取方法上的注解对象
        GmallCache gmallCache = method.getAnnotation(GmallCache.class);

        //获取缓存前缀
        String prefix = gmallCache.prefix();
        //方法的形参列表
        Object[] args = joinPoint.getArgs();
        //组装缓存的key
        String argString = StringUtil.join(args, ",");
        String key = prefix + argString;

        //布隆过滤器内初始化加入了mysql内的数据,先查询一次过滤器内是否有数据,直接避免了缓存穿透问题也节约了查询时间
        //为了防止缓存穿透,使用布隆过滤器
        if (!bloomFilter.contains(key)){
            return null;
        }


        //1.先查缓存
        String json = redisTemplate.opsForValue().get(key);
        if (StringUtils.isNotBlank(json)) {
            return JSON.parseObject(json, signature.getReturnType());
        }

        //2.加分布式锁:防止缓存击穿
        RLock lock = redissonClient.getLock(gmallCache.lock() + argString);
        lock.lock();

        try {
            //3.再查缓存
            String json2 = redisTemplate.opsForValue().get(key);
            if (StringUtils.isNotBlank(json2)) {
                return JSON.parseObject(json2, signature.getReturnType());
            }

            //4.执行目标方法
            Object result = joinPoint.proceed(args);

            //5.放入缓存并释放分布式锁
            if (result != null) {
                redisTemplate.opsForValue().set(key, JSON.toJSONString(result), gmallCache.timeout() + new Random().nextInt(gmallCache.random()), TimeUnit.MINUTES);
            }

            return result;
        } finally {
            lock.unlock();
        }
    }

}
